package com.example.lib_common

import android.content.Context
import android.os.Build
import android.util.TypedValue
import androidx.annotation.RequiresApi
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * @author yaotianxue
 * @description
 * @date 2025/1/16
 */

//获取属性值：顶层函数：静态
fun getAttrValue(context: Context, attrId:Int):Int{
    val typedArray = TypedValue()
    context.theme.resolveAttribute(attrId,typedArray,true)
    return typedArray.data
}



//扩展函数
fun <T> Flow<T>.observeWithLifecycle(
    lifecycleOwner: LifecycleOwner,
    minState: Lifecycle.State = Lifecycle.State.STARTED,
    action: suspend (T)->Unit
): Job = lifecycleOwner.lifecycleScope.launch {
    lifecycleOwner.repeatOnLifecycle(minState){
        collectLatest {
            action.invoke(it)
        }
    }
}

//获得当前版本号
@RequiresApi(Build.VERSION_CODES.P)
fun getVersionCode(context: Context):Long{
    val packageManager = context.packageManager
    val packageInfo = packageManager.getPackageInfo(context.packageName,0)
    return packageInfo.longVersionCode
}

//处理url的参数  type=1&id=4  -->map集合
fun getUrlParams(urlParams:String):Map<String,String>{
    val map = mutableMapOf<String,String>()
    val params = urlParams.split("&".toRegex()).toTypedArray() //切割后数据
    for (param in params){//type=1    id=4
        val p =  param.split("=".toRegex()).toTypedArray() //type 1
        if(p.size == 2){
            map[p[0]] = p[1]
        }
    }
    return map

}


